package com.neutech.service.impl;

import com.neutech.dao.CartDAO;
import com.neutech.dao.FoodDAO;
import com.neutech.dao.impl.CartDAOImpl;
import com.neutech.dao.impl.FoodDAOImpl;
import com.neutech.entity.Cart;
import com.neutech.entity.Food;
import com.neutech.service.CartService;
import com.neutech.vo.ResultVO;

public class CartServiceImpl implements CartService {

    private FoodDAO foodDAO = new FoodDAOImpl();

    private CartDAO cartDAO = new CartDAOImpl();
    @Override
    public ResultVO add(Integer foodId, Integer quantity, Integer userId) {
        //校验参数
        Food food = foodDAO.getById(foodId);

        if (food == null) {
            return ResultVO.error(4001, "数据不合法");
        }

        //重复商品判断
        //重复数量+quantity
        //不重复新增数据
        Cart cartData = cartDAO.getByFoodIdAndUserId(foodId, userId);
        if (cartData == null) {
            //增加逻辑
            Cart cart = new Cart();
            cart.setFoodId(food.getId());
            cart.setFoodName(food.getName());
            cart.setFoodMainImage(food.getMainImage());
            cart.setFoodPrice(food.getPrice());
            cart.setBusinessId(food.getBusinessId());
            cart.setUserId(userId);
            cart.setQuantity(quantity);
            System.out.println(111);
            cartDAO.add(cart);
        } else {
            //修改逻辑
            cartData.setQuantity(cartData.getQuantity() + quantity);
            cartDAO.updateQuantity(cartData);
        }

        return ResultVO.success();
    }

    @Override
    public ResultVO listCartByUserId(Integer userId) {
        return ResultVO.success(cartDAO.listByUserId(userId));
    }

    @Override
    public ResultVO updateQuantityById(Integer id, Integer quantity, Integer userId) {
        Cart cart = cartDAO.getByIdAndUserId(id, userId);
        if (cart == null) {
            return ResultVO.error(1005, "数据不合法");
        }
        cart.setQuantity(quantity);
        // 校验id是否存在
        cartDAO.updateQuantity(cart);
        return ResultVO.success();
    }
}
